<template>
	<slot />

	<div ref="loadingTarget" class="h-6 py-4">
		<!-- 加载更多 -->
		<m-svg-icon
			v-show="loading"
			class="w-4 h-4 mx-auto animate-spin"
			name="infinite-load"
		></m-svg-icon>

		<!-- 没有更多数据了 -->
		<p v-if="isFinished" class="text-center text-base text-zinc-400">
			没有更多数据了
		</p>
	</div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useIntersectionObserver, useVModel } from '@vueuse/core'

const emits = defineEmits(['update:modelValue', 'onload'])
const props = defineProps({
	modelValue: {
		type: Boolean,
		required: true,
	},
	isFinished: {
		type: Boolean,
		default: false,
	},
})
const loading = useVModel(props)

// 记录当前是否在底部
const targetIsIntersecting = ref(false)

const loadingTarget = ref(null)
useIntersectionObserver(loadingTarget, ([{ isIntersecting }]) => {
	targetIsIntersecting.value = isIntersecting
	emitLoad()
})

// 触发Load事件
const emitLoad = () => {
	setTimeout(() => {
		if (targetIsIntersecting.value && !loading.value && !props.isFinished) {
			loading.value = true
			emits('onload')
		}
	}, 200)
}

// 监听loading的变化， 解决数据加载 完成之后，首屏未铺满的问题
watch(loading, emitLoad)
</script>

<style scoped lang="scss"></style>
